package org.i1510.common.servlet;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.session.mgt.SessionKey;
import org.i1510.common.utils.StringUtils;
import org.i1510.common.utils.web.WebUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * This Servlet does not do anything useful, just prints "Hello World!". The
 * intent is to help you to get started if you want to build your own Controller
 * servlet that uses FreeMarker for the View. For more advanced example, see the
 * 2nd Web application example.
 */
public class RedirectServlet extends HttpServlet {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Configuration cfg; 
    
    public void init() {
        // Initialize the FreeMarker configuration;
        // - Create a configuration instance
        cfg = new Configuration();
        // - Templates are stoted in the WEB-INF/templates directory of the Web app.
        cfg.setServletContextForTemplateLoading(
                getServletContext(), "/");
       
        // In a real-world application various other settings should be explicitly
        // set here, but for the sake of brevity we leave it out now. See the
        // "webapp2" example for them.
    }
    
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        // Build the data-model
        Map root = new HashMap();

        String url = req.getRequestURI();
//	    String regex = "[\\w,/]+";
//		Pattern pattern = Pattern.compile(regex);
//		Matcher m = pattern.matcher(url);
//		String tmpath = "";
//		while(m.find()){
//			tmpath = m.group();
//		}
		
		String templatePath = StringUtils.subStringAfter(url,"/",2);
//		templatePath = templatePath.replace(".html", ".ftl");
		templatePath = templatePath.replace(".html", "/index.ftl");
		
        // Get the templat object
        Template t = cfg.getTemplate("WEB-INF/template/ftl/"+templatePath,"UTF-8");
        System.out.println("访问html文件正在读取映射ftl:tmpath="+templatePath);
        // Prepare the HTTP response:
        // - Use the charset of template for the output
        // - Use text/html MIME-type
        resp.setContentType("text/html; charset=UTF-8" );//+ t.getEncoding()
        Writer out = resp.getWriter();
        
        // Merge the data-model and the template
        try {
        	cfg.setSharedVariable("ctx", req.getContextPath());
        	cfg.setSharedVariable("actx", req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+req.getContextPath());
        	cfg.setSharedVariable("request", WebUtils.toAttributeMap(req)); 
        	
            t.process(root, out);
        } catch (TemplateException e) {
            throw new ServletException("Error while processing FreeMarker template", e);
        }
    }

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
    
}